package com.koron.order.linedefect.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.koron.bean.system.staff.po.AppUserPo;
import com.koron.common.core.util.StringUtils;
import com.koron.common.core.util.message.MessageUtil;
import com.koron.order.change.dispatch.mapper.ChangeDispatchMapper;
import com.koron.order.change.util.ThreadLocalOrderChange;
import com.koron.order.common.bean.base.OrderType;
import com.koron.order.common.bean.dto.OrderDispatchDto;
import com.koron.order.common.bean.po.OrderDispatch;
import com.koron.order.common.bean.po.OrderLocationPo;
import com.koron.order.common.bean.po.OrderReassignPo;
import com.koron.order.common.service.*;
import com.koron.order.defect.bean.convertor.DefectConvertor;
import com.koron.order.defect.bean.po.DefectDispatch;
import com.koron.order.defect.bean.po.DefectStatus;
import com.koron.order.defect.bean.vo.DispatchVO;
import com.koron.order.defect.mapper.DispatchMapper;
import com.koron.order.defect.service.DefectDispatchService;
import com.koron.order.linedefect.base.bean.convertor.LineDefectConvertor;
import com.koron.order.linedefect.base.bean.dto.DefectDTO;
import com.koron.order.linedefect.base.service.DefectService;
import com.koron.order.linedefect.base.service.DispatchService;
import org.apache.commons.collections4.CollectionUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName DispatchServiceImpl
 * @description
 * @Author zhouj
 * @Date 2021/9/3 17:50
 */
@Service("lineDispatchService")
public class DispatchServiceImpl implements DispatchService {

    @Autowired
    DefectDispatchService defectDispatchService;

    @Autowired
    OrderDispatchInfoService orderDispatchInfoService;

    @Autowired
    OrderDispatchService orderDispatchService;

    @Autowired
    OrderDispatchWorkerService orderDispatchWorkerService;

    @Autowired
    DefectService lineDefectService;

    @Autowired
    DefectConvertor defectConvertor;

    @Autowired
    LineDefectConvertor lineDefectConvertor;

    /*工单的工作地点*/
    @Autowired
    OrderWorkDeptService orderWorkDeptService;

    @Autowired
    OrderReassignService orderReassignService;

    /*工单的工作地点*/
    @Autowired
    OrderLocationService orderLocationService;

    @Autowired
    MessageUtil messageUtil;

    //查询单个派单详情
    @Override
    @TaskAnnotation("querySingle")
    public DispatchVO querySingle(SessionFactory factory, DispatchVO dispatchVO) {

        DispatchMapper mapper = getDispatchMapper(factory);
        DispatchVO dispatchVO1 = mapper.querySingle(dispatchVO);

        return dispatchVO1;
    }

    //保存三个表单派工信息的信息
    @Override
    @TaskAnnotation("saveDispatch")
    public String saveDispatch(SessionFactory factory, DispatchVO dispatchVO) {

        //vo转工单派工bean
        OrderDispatchDto orderDispatchDto = defectConvertor.voToOrderDispatchDto(dispatchVO);
        String orderId = dispatchVO.getOrderId();

        //1.1 派工信息表
        String dispatchId = orderDispatchInfoService.insertOrUpdate(factory, orderDispatchDto);

        //1.2 工作地点关联表
        List<OrderLocationPo> orderLocationList = dispatchVO.getOrderLocationList();
        //不为空则赋值
        if (CollectionUtils.isNotEmpty(orderLocationList)) {
            orderLocationList.forEach(p->{
                p.setOrderId(dispatchVO.getOrderId());
                p.setOrderType(OrderType.DEFECT);
            });
            orderLocationService.insertBatch(factory,orderLocationList);
        }else {
            orderLocationService.deleteByOrderId(factory,orderId);
        }

        //vo转缺陷派工bean
        DefectDispatch defectDispatch = defectConvertor.voToDefectDispatchBean(dispatchVO);
        defectDispatch.setDefectId(orderDispatchDto.getOrderId());

        //1.3 缺陷派工表
        defectDispatchService.insertOrUpdate(factory, defectDispatch);

        if (dispatchVO.getIsCommit()) {
            //修改工单状态 待派工-->执行中
            lineDefectService.submitDefect(factory, dispatchVO.getOrderId(), DefectStatus.IN_EXECUTE.getStatus());

            //修改转派工单的派工状态
            OrderReassignPo orderReassignPo = new OrderReassignPo();
            orderReassignPo.setOrderId(dispatchVO.getOrderId());
            orderReassignPo.setDispatch(true);
            orderReassignPo.setWorker(getCurrUser().getAccount());
            orderReassignService.updateByOrderId(factory, orderReassignPo);

            // 缺陷工单发送派工通知
            if (StringUtils.isNotEmpty(orderDispatchDto.getTopicWorker())){
                String topicWorkerJson = orderDispatchDto.getTopicWorker();
                List<AppUserPo> userPoList = JSONUtil.parseArray(topicWorkerJson).toList(AppUserPo.class);
                String handler = userPoList.stream().map(AppUserPo::getAccount).collect(Collectors.joining(","));
                sendMessage(handler,orderDispatchDto);
            }
        }

        return dispatchId;

    }

    private void sendMessage(String handler, OrderDispatch orderDispatch) {
        String qywxHref = messageUtil.generateQywxHref("transmit_" + orderDispatch.getOrderType() + "_order", orderDispatch.getOrderId(),"","");
        messageUtil.sendMessageWithTemplate("dispatch_notice", qywxHref, handler, orderDispatch.getContext());
    }

    @Override
    @TaskAnnotation("deleteByOrderId")
    public int deleteByOrderId(SessionFactory factory, String orderId) {

        orderDispatchService.deleteByOrderId(factory, orderId);
        orderDispatchWorkerService.deleteByOrderId(factory, orderId);
        defectDispatchService.deleteByOrderId(factory, orderId);
        orderWorkDeptService.deleteByOrderId(factory, orderId);

        return 1;
    }

    //转派工单
    @Override
    @TaskAnnotation("reassign")
    public OrderReassignPo reassign(SessionFactory factory, OrderReassignPo orderReassignPo) {

        orderReassignPo.setOrderType(OrderType.DEFECT);
        orderReassignService.insertOrUpdate(factory, orderReassignPo);

        //工单修改为待派工状态
        DefectDTO defectDTO = new DefectDTO();
        defectDTO.setId(orderReassignPo.getOrderId());
        defectDTO.setMajor(orderReassignPo.getMajor());
        defectDTO.setStatus(DefectStatus.WAIT_DISPATCH.getStatus());
        lineDefectService.update(factory, defectDTO);

        return orderReassignPo;
    }

    @TaskAnnotation("update")
    @Override
    public int update(SessionFactory factory, DispatchVO dispatchVO) {
        DefectDispatch defectDispatch = new DefectDispatch();
        BeanUtil.copyProperties(dispatchVO,defectDispatch,true);
        defectDispatch.setId(dispatchVO.getOrderDispatchId());
        return defectDispatchService.update(factory, defectDispatch);
    }

    DispatchMapper getDispatchMapper(SessionFactory factory) {

        if (OrderType.CHANGE.equals(ThreadLocalOrderChange.get())) {
            return factory.getMapper(ChangeDispatchMapper.class);
        }

        return factory.getMapper(DispatchMapper.class);
    }

}
